/**
 * @developer：MR·Feng
 * 账单
 */

import styles from '@/styles/bill/bill.less';

import _ from 'lodash';
import moment from 'moment';
import { withRouter } from 'umi';
import React, { useEffect, useState } from 'react';
import {
    Table,
    Space,
    Form,
    Modal,
    DatePicker,
    Input,
    Button,
    Select,
    message,
} from 'antd';
import { layout } from '@/utils/datas';
import Request from '@/api/baseRequest';

const { Option } = Select;

function Bill({ history, location }) {
    const { state } = location;
    const [parameter] = useState(_.cloneDeep(state));
    const [form] = Form.useForm();
    const [formResource] = Form.useForm();
    const [account, setaccount] = useState([]);
    const [billlist, setbilllist] = useState({});
    const [update, setupdate] = useState(false);
    const [loading, setloading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [pagination, setpagination] = useState(
        parameter ? parameter.pagination : { current: 1, pageSize: 10 },
    );

    // table显示格式
    const columns = [
        {
            title: '资源id',
            dataIndex: 'resourcesId',
            align: 'center',
            width: '20%',
        },
        {
            title: '实例名称',
            dataIndex: 'name',
            align: 'center',
            width: '20%',
        },
        {
            title: '类型',
            dataIndex: 'type',
            align: 'center',
            width: '20%',
        },
        {
            title: '成本',
            dataIndex: 'cost',
            align: 'center',
            width: '10%',
            render: (text) => <>&yen;{text}</>,
        },
        {
            title: '比例',
            dataIndex: 'bili',
            align: 'center',
            width: '10%',
            render: (text) => (
                <span className={text !== 100 ? styles.red : styles.green}>
                    {text}%
                </span>
            ),
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: '20%',
            align: 'center',
            key: 'id',
            render: (text, record) => (
                <Space size="middle" className={styles.operation}>
                    <span onClick={() => handleResourse(record)}>详情</span>
                    <span onClick={() => handleEdit(record)}>编辑</span>
                </Space>
            ),
        },
    ];

    const handleResourse = (val) => {
        let billform = _.cloneDeep(form.getFieldValue());
        billform.month = moment(billform.month).format('YYYY-MM');
        let data = { ...val, ...{ pagination }, ...{ billform } };
        history.push({ pathname: '/bill/detail', state: data });
    };

    // 编辑实例名称
    const handleEdit = (val) => {
        formResource.setFieldsValue({
            name: val.name,
            bill_id: val.id,
            action: 'modify',
        });
        setIsModalVisible(true);
    };
    // 蒙层确定操作
    const handleCreate = () => {
        formResource
            .validateFields()
            .then(() => {
                let params = _.cloneDeep(formResource.getFieldValue());
                handleCreateEditDelete(params);
                setIsModalVisible(false);
                formResource.resetFields();
            })
            .catch(() => {
                message.warning('请填写必填项');
            });
    };
    // 编辑
    const handleCreateEditDelete = (params) => {
        Request.postBill(params).then((res) => {
            if ([200, '200', 'OK'].includes(res.status)) {
                message.success(res.message || '添加成功');
                setupdate(!update);
            }
        });
    };
    // 蒙层返回操作
    const handleCancel = () => setIsModalVisible(false);

    // 页数改变
    const handleTableChange = (pagination) => setpagination(pagination);

    // 子公司名称选择
    const onChange = (value) => form.setFieldsValue({ id: value });

    // 获取最新账单
    const getAllBill = async (val) => {
        // await setpagination({ ...{ pagination }, ...{ current: 1 } });
        let params = val
            ? { ...pagination, ...{ current: 1 } }
            : { ...pagination };
        await setpagination(params);
        let getbillform = _.cloneDeep(form.getFieldValue());
        getbillform.month = moment(getbillform.month).format('YYYY-MM');
        let { status, data } = await Request.getBill(getbillform);
        if (status === '200') {
            const okeys = Object.keys(data.data);
            const ovalues = Object.values(data.data);
            let changeValues = ovalues.map((item, inde) => {
                item['resourcesId'] = okeys[inde];
                return item;
            });
            setbilllist({
                count: data.count,
                data: changeValues || [],
            });
            setloading(false);
        }
    };

    // 保存账单
    const saveAllBill = async (val) => {
        let getbillform = _.cloneDeep(form.getFieldValue());
        getbillform.month = moment(getbillform.month).format('YYYY-MM');
        getbillform.action = val || 'save';
        let result = await Request.postBill(getbillform);
        if (result.status === '200') {
            message.success(result.message || '保存成功');
        }
    };

    // table footer
    const tableFooter = () => (
        <aside className={styles.tableFooter}>
            当月消费总额：&yen;{billlist.count}
        </aside>
    );

    // 副作用操作
    useEffect(async () => {
        setloading(true);
        if (!form.getFieldValue('id')) {
            let result = await Request.getAccount();
            setaccount(result.data);
            form.setFieldsValue({
                id: parameter ? parameter.id : result.data[0].id,
                month: parameter ? moment(parameter.month) : moment(),
            });
        }
        getAllBill();

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [update]);

    return (
        <section className={styles.bill}>
            <Form
                {...layout}
                layout="inline"
                form={form}
                onFinish={() => getAllBill(1)}
                className={styles.billForm}
            >
                <Form.Item label="ak名称" name="id">
                    <Select
                        showSearch
                        style={{ width: 200 }}
                        placeholder="请选择AK账号"
                        onChange={onChange}
                    >
                        {(account || []).map((item) => (
                            <Option key={item.passwd} value={item.id}>
                                {item.name}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="月份" name="month">
                    <DatePicker picker="month" />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        查询
                    </Button>
                    <Button onClick={() => saveAllBill()}>保存</Button>
                    <Button onClick={() => saveAllBill('calculate')}>
                        计算
                    </Button>
                </Form.Item>
            </Form>
            <Modal
                title="编辑实例名称"
                visible={isModalVisible}
                onOk={handleCreate}
                onCancel={handleCancel}
            >
                <Form
                    {...layout}
                    form={formResource}
                    className={styles.accountForm}
                >
                    <Form.Item
                        label="name"
                        name="name"
                        rules={[
                            { required: true, message: 'Please input name!' },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
            <Table
                columns={columns}
                rowKey={(record) => record.resourcesId}
                dataSource={billlist.data}
                pagination={pagination}
                loading={loading}
                footer={tableFooter}
                onChange={handleTableChange}
            />
        </section>
    );
}

export default withRouter(Bill);
